//
//  LBCalendarContentView.m
//  Masonry
//
//  Created by 杨庆人 on 2018/4/24.
//  Copyright © 2018年 杨庆人. All rights reserved.
//

#import "LBCalendarContentView.h"
#import "FSCalendar.h"
#import "NSDate+GFCalendar.h"
#import <LBCategory/UIColor+LBColor.h>
#import <LBCategory/NSString+LBDate.h>

#define gray [UIColor colorWithR:148 G:152 B:159]
#define light_gray [UIColor colorWithR:223 G:228 B:238]
#define calendar_H ([[UIDevice currentDevice].model hasPrefix:@"iPad"] ? 465 : 315)
@interface LBCalendarContentView ()<FSCalendarDataSource,FSCalendarDelegate>

@property (weak, nonatomic) FSCalendar *calendar;
@property (weak, nonatomic) UIButton *previousButton;
@property (weak, nonatomic) UIButton *nextButton;
@property (strong, nonatomic) NSCalendar *gregorian;
@property (nonatomic,assign)BOOL isLastOrNextMonButtonAnimated;
@property (nonatomic,assign)BOOL isLastOrNextMonDayAnimated;
@property (assign, nonatomic) LBCalendarPickerType type;
@property (nonatomic,copy)NSString *format;

- (void)previousClicked:(id)sender;
- (void)nextClicked:(id)sender;

@end
@implementation LBCalendarContentView

- (instancetype)initWithFrame:(CGRect)frame type:(LBCalendarPickerType)type {
    return [self initWithFrame:frame type:type format:nil];
}

- (instancetype)initWithFrame:(CGRect)frame type:(LBCalendarPickerType)type format:(NSString *)format {
    if (self = [super initWithFrame:frame]) {
        _timeStampType = LBCalendarTimeStampTypeDayEnd;
        _isLastOrNextMonButtonAnimated = YES;
        _isLastOrNextMonDayAnimated = YES;
        _type = type;
        _format = format;
        [self setCalendarContentView];
    }
    return self;
}

- (void)setCalendarContentView {
    
    self.backgroundColor = [UIColor whiteColor];
    
    self.gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    // 450 for iPad and 300 for iPhone
    
    FSCalendar *calendar = [[FSCalendar alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, [self.class viewHight])];
    
    calendar.headerHeight = 50;
    calendar.weekdayHeight = 30;
    calendar.scrollEnabled = NO;
    
    // 选择默认
    if (LBCalendarPickerSelectDateNormal == self.type ||
        LBCalendarPickerNoSelectLastDate == self.type ||
        LBCalendarPickerNoSelectNextDate == self.type) {
        [calendar selectDate:[NSDate date]];
    }

    calendar.dataSource = self;
    calendar.delegate = self;
    calendar.backgroundColor = [UIColor whiteColor];
    
    // title
    calendar.appearance.headerDateFormat = @"yyyy年 MM月";
    calendar.appearance.titleFont = [UIFont systemFontOfSize:16];
    calendar.appearance.headerTitleColor = [UIColor colorWithR:0 G:28 B:45];
    
    // week
    calendar.appearance.weekdayTextColor = [UIColor colorWithR:153 G:165 B:182];
    
    // today
    calendar.appearance.todayColor = [UIColor clearColor];
    calendar.appearance.titleTodayColor = gray;
    
    calendar.appearance.selectionColor = [UIColor blue];
    
    calendar.appearance.headerMinimumDissolvedAlpha = 0;
    calendar.appearance.caseOptions = FSCalendarCaseOptionsHeaderUsesUpperCase;
    
    [self addSubview:calendar];
    self.calendar = calendar;
    
    UIButton *previousButton = [UIButton buttonWithType:UIButtonTypeCustom];
    previousButton.frame = CGRectMake(0, 10, 100, 34);
    previousButton.backgroundColor = [UIColor whiteColor];
    previousButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [previousButton setImage:[UIImage imageNamed:@"LBCalendarPickerView.bundle/L"] forState:UIControlStateNormal];
    [previousButton addTarget:self action:@selector(previousClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:previousButton];
    self.previousButton = previousButton;
    
    UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    nextButton.frame = CGRectMake(CGRectGetWidth(self.frame) - 100, 10, 95, 34);
    nextButton.backgroundColor = [UIColor whiteColor];
    nextButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [nextButton setImage:[UIImage imageNamed:@"LBCalendarPickerView.bundle/R"] forState:UIControlStateNormal];
    [nextButton addTarget:self action:@selector(nextClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:nextButton];
    self.nextButton = nextButton;
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, self.bounds.size.height - 1, self.bounds.size.width, 2)];
    line.backgroundColor = [UIColor whiteColor];
    [self addSubview:line];
    
    UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(0, -1, self.bounds.size.width, 2)];
    line1.backgroundColor = [UIColor whiteColor];
    [self addSubview:line1];
}

- (void)nextClicked:(id)sender {
    [self nextClickedAnimated:self.isLastOrNextMonButtonAnimated];
}

- (void)previousClicked:(id)sender {
    [self previousClickedAnimated:self.isLastOrNextMonButtonAnimated];
}

- (void)nextClickedAnimated:(BOOL)animated {
    NSDate *currentMonth = self.calendar.currentPage;
    NSDate *nextMonth = [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:1 toDate:currentMonth options:0];
    
    if (self.monthButtonClick) {
        // NSDate转为毫秒时间戳
        NSTimeInterval a = [nextMonth timeIntervalSince1970] * 1000;
        NSString *timeStamp = [NSString stringWithFormat:@"%.0f",a];
        self.monthButtonClick(timeStamp,[nextMonth totalDaysInMonth]);
    }
    [self.calendar setCurrentPage:nextMonth animated:animated];
}

- (void)previousClickedAnimated:(BOOL)animated {
    NSDate *currentMonth = self.calendar.currentPage;
    NSDate *previousMonth = [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:-1 toDate:currentMonth options:0];
    
    if (self.monthButtonClick) {
        // NSDate转为毫秒时间戳
        NSTimeInterval a = [previousMonth timeIntervalSince1970] * 1000;
        NSString *timeStamp = [NSString stringWithFormat:@"%.0f",a];
        self.monthButtonClick(timeStamp,[previousMonth totalDaysInMonth]);
    }
    [self.calendar setCurrentPage:previousMonth animated:animated];
}


- (BOOL)calendar:(FSCalendar *)calendar shouldSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition {
    if (LBCalendarPickerNoSelectLastDate == self.type) {
        if (([date dateYear] < [[NSDate date] dateYear]) || (([date dateMonth] < [[NSDate date] dateMonth]) && ([date dateYear] == [[NSDate date] dateYear])) ||
            (([date dateMonth] == [[NSDate date] dateMonth]) && ([date dateYear] == [[NSDate date] dateYear]) && ([date dateDay] < [[NSDate date] dateDay]))) {
            
            return NO;
        }
        else {
            return YES;
        }
    }
    else if (LBCalendarPickerNoSelectLastAndTodayDate == self.type) {
        if (([date dateYear] < [[NSDate date] dateYear]) || (([date dateMonth] < [[NSDate date] dateMonth]) && ([date dateYear] == [[NSDate date] dateYear])) ||
            (([date dateMonth] == [[NSDate date] dateMonth]) && ([date dateYear] == [[NSDate date] dateYear]) && ([date dateDay] <= [[NSDate date] dateDay]))) {
            
            return NO;
        }
        else {
            return YES;
        }
    }
    else if (LBCalendarPickerNoSelectNextDate == self.type) {
        if (([date dateYear] > [[NSDate date] dateYear]) || (([date dateMonth] > [[NSDate date] dateMonth]) && ([date dateYear] == [[NSDate date] dateYear])) ||
            (([date dateMonth] == [[NSDate date] dateMonth]) && ([date dateYear] == [[NSDate date] dateYear]) && ([date dateDay] > [[NSDate date] dateDay]))) {
            
            return NO;
        }
        else {
            return YES;
        }
    }
    else if (LBCalendarPickerNoSelectNextAndTodayDate == self.type) {
        if (([date dateYear] > [[NSDate date] dateYear]) || (([date dateMonth] > [[NSDate date] dateMonth]) && ([date dateYear] == [[NSDate date] dateYear])) ||
            (([date dateMonth] == [[NSDate date] dateMonth]) && ([date dateYear] == [[NSDate date] dateYear]) && ([date dateDay] >= [[NSDate date] dateDay]))) {
            
            return NO;
        }
        else {
            return YES;
        }
    }
    else {
        return YES;
    }
}

- (nullable UIColor *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance titleDefaultColorForDate:(NSDate *)date {
    if (LBCalendarPickerNoSelectLastDate == self.type) {
        if ([calendar.currentPage dateYear] > [[NSDate date] dateYear] || ([calendar.currentPage dateYear] == [[NSDate date] dateYear] && [calendar.currentPage dateMonth] > [[NSDate date] dateMonth])) {
            return [self.class titleColorWithCalendar:calendar appearance:appearance titleDefaultColorForDate:date];
        }
        
        if (([date dateYear] < [[NSDate date] dateYear]) || (([date dateMonth] < [[NSDate date] dateMonth]) && ([date dateYear] == [[NSDate date] dateYear])) ||
            (([date dateMonth] == [[NSDate date] dateMonth]) && ([date dateYear] == [[NSDate date] dateYear]) && ([date dateDay] < [[NSDate date] dateDay]))) {
            
            return light_gray;
        }
        else {
            return gray;
        }
    }
    else if (LBCalendarPickerNoSelectLastAndTodayDate == self.type) {
        if ([calendar.currentPage dateYear] > [[NSDate date] dateYear] || ([calendar.currentPage dateYear] == [[NSDate date] dateYear] && [calendar.currentPage dateMonth] > [[NSDate date] dateMonth])) {
            return [self.class titleColorWithCalendar:calendar appearance:appearance titleDefaultColorForDate:date];
        }
        
        if (([date dateYear] < [[NSDate date] dateYear]) || (([date dateMonth] < [[NSDate date] dateMonth]) && ([date dateYear] == [[NSDate date] dateYear])) ||
            (([date dateMonth] == [[NSDate date] dateMonth]) && ([date dateYear] == [[NSDate date] dateYear]) && ([date dateDay] <= [[NSDate date] dateDay]))) {
            
            return light_gray;
        }
        else {
            return gray;
        }
    }
    else if (LBCalendarPickerNoSelectNextDate == self.type) {
        
        if ([calendar.currentPage dateYear] < [[NSDate date] dateYear] || ([calendar.currentPage dateYear] == [[NSDate date] dateYear] && [calendar.currentPage dateMonth] < [[NSDate date] dateMonth])) {
            return [self.class titleColorWithCalendar:calendar appearance:appearance titleDefaultColorForDate:date];
        }
        
        if (([date dateYear] > [[NSDate date] dateYear]) || (([date dateMonth] > [[NSDate date] dateMonth]) && ([date dateYear] == [[NSDate date] dateYear])) ||
            (([date dateMonth] == [[NSDate date] dateMonth]) && ([date dateYear] == [[NSDate date] dateYear]) && ([date dateDay] > [[NSDate date] dateDay]))) {
            return light_gray;
        }
        else {
            return gray;
        }
    }
    else if (LBCalendarPickerNoSelectNextAndTodayDate == self.type) {
        
        if ([calendar.currentPage dateYear] < [[NSDate date] dateYear] || ([calendar.currentPage dateYear] == [[NSDate date] dateYear] && [calendar.currentPage dateMonth] < [[NSDate date] dateMonth])) {
            return [self.class titleColorWithCalendar:calendar appearance:appearance titleDefaultColorForDate:date];
        }
        
        if (([date dateYear] > [[NSDate date] dateYear]) || (([date dateMonth] > [[NSDate date] dateMonth]) && ([date dateYear] == [[NSDate date] dateYear])) ||
            (([date dateMonth] == [[NSDate date] dateMonth]) && ([date dateYear] == [[NSDate date] dateYear]) && ([date dateDay] >= [[NSDate date] dateDay]))) {
            return light_gray;
        }
        else {
            return gray;
        }
    }
    else {
        return [self.class titleColorWithCalendar:calendar appearance:appearance titleDefaultColorForDate:date];
    }
}

+ (UIColor *)titleColorWithCalendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance titleDefaultColorForDate:(NSDate *)date {
    if (([date dateYear] != [calendar.currentPage dateYear]) ||
        ([date dateYear] == [calendar.currentPage dateYear] && [date dateMonth] != [calendar.currentPage dateMonth])) {
        return light_gray;
    }
    else {
        return gray;
    }
}

- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date {
    // didSelect..
    
    if (([date dateYear] > [calendar.currentPage dateYear]) || (([date dateMonth] > [calendar.currentPage dateMonth]) && ([date dateYear] == [calendar.currentPage dateYear]))) {
        [self nextClickedAnimated:self.isLastOrNextMonDayAnimated];
    }
    else if (([date dateYear] < [calendar.currentPage dateYear]) || (([date dateMonth] < [calendar.currentPage dateMonth]) && ([date dateYear] == [calendar.currentPage dateYear]))) {
        [self previousClickedAnimated:self.isLastOrNextMonDayAnimated];
    }
    
    NSString *timeStamp;
    if (LBCalendarTimeStampTypeDayStart == self.timeStampType) {
        timeStamp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970] *1000];
    }
    else {
        timeStamp = [NSString stringWithFormat:@"%ld", (long)([date timeIntervalSince1970] + NSStringDateTimeDAY - 1) *1000];
    }
    
    NSString *timeStr = nil;
    if (self.format) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = self.format;
        timeStr = [NSString stringFromTimeIntervalStr:timeStamp withFormat:self.format];
    }
    
    !self.select ? :self.select(timeStamp,timeStr);
}

+ (CGFloat)viewHight {
    CGFloat height = calendar_H;
    return height;
}

/**
 设置默认选中，不会触发selectBlock
 
 @param timeStamp 毫秒时间戳
 */
- (void)setDefaultSelectDay:(NSString *)timeStamp {
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:([timeStamp doubleValue] / 1000)];
    [self.calendar selectDate:date];
}

// 点击上个月、下个月的按钮，是否需要动画滑动，默认 YES
- (void)setLastOrNextMonButtonAnimated:(BOOL)animated {
    self.isLastOrNextMonButtonAnimated = animated;
}

// 选中上个月、下个月的日期，是否需要动画滑动，默认 YES
- (void)setLastOrNextMonDayAnimated:(BOOL)animated {
    self.isLastOrNextMonDayAnimated = animated;
}


@end

